package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.Null;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //构造日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String joinString = StringUtils.join(dateList, ",");



        //每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate Date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(Date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(Date, LocalTime.MAX);
            //查询每天的营业额
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double d = orderMapper.turnoverStatistics(map);
             d =  d == null ? 0.0 : d;
            turnoverList.add(d);
        }
        String turnoverString = StringUtils.join(turnoverList, ",");



        TurnoverReportVO build = TurnoverReportVO.builder()
                .dateList(joinString)
                .turnoverList(turnoverString)
                .build();
        return build;
    }


    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //添加时间
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dateString = StringUtils.join(dateList, ",");


        //新增用户
        List<Integer> newUserList = new ArrayList<>();
        //总用户
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate data : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(data, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(data, LocalTime.MAX);
            Map map = new HashMap<>();
            //先添加总的用户
            map.put("end",endTime);
            Integer totalUser = userMapper.userStatistics(map);
            totalUser = totalUser == null ? 0 :totalUser;

            //再添加新用户
            map.put("begin",beginTime);
            Integer newUser = userMapper.userStatistics(map);
            newUser =  newUser == null ? 0: newUser;


            totalUserList.add(totalUser);
            newUserList.add(newUser);

        }

        String newUserString = StringUtils.join(newUserList, ",");
        String totalUserString = StringUtils.join(totalUserList, ",");

        UserReportVO userRepotrVO = UserReportVO.builder()
                .dateList(dateString)
                .totalUserList(totalUserString)
                .newUserList(newUserString)
                .build();

        return userRepotrVO;
    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //添加时间
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        String dateString = StringUtils.join(dateList, ",");


        //每天有效订单数
        List<Integer> validOrderList = new ArrayList<>();
        //每天总订单数
        List<Integer> totalOrderList = new ArrayList<>();
        for (LocalDate data : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(data, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(data, LocalTime.MAX);
            // select count(id) from orders where order_time > ? and order_time < ? and status = ?
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            //orderStatistics统计总订单数和有效订单数
            Integer totalOrder = orderMapper.orderStatistics(map);
            totalOrder = totalOrder == null ?  0 : totalOrder;
            //统计有效订单数
            map.put("status",Orders.COMPLETED);
            Integer validOrder = orderMapper.orderStatistics(map);
            validOrder = validOrder == null? 0 : validOrder;

            //再把它们加入到集合
            validOrderList.add(validOrder);
            totalOrderList.add(totalOrder);
        }
        String validOrderString = StringUtils.join(validOrderList, ",");
        String totalOrderString = StringUtils.join(totalOrderList, ",");

        //有效订单总数
        Integer validOrderTotal = 0;
        for (Integer validOrder : validOrderList) {
            validOrderTotal = validOrderTotal + validOrder;
        }

        //总的订单总数
        Integer totalOrderTotal = 0;
        for (Integer totalOrder : totalOrderList) {
            totalOrderTotal  = totalOrderTotal +  totalOrder;
        }

        Double p = 0.0;
        if (totalOrderTotal != 0){
            p = validOrderTotal.doubleValue() / totalOrderTotal;
        }
        OrderReportVO build = OrderReportVO.builder()
                .dateList(dateString)
                .orderCountList(totalOrderString)  //每日订单数
                .orderCompletionRate(p)     //订单完成率
                .totalOrderCount(totalOrderTotal)     //订单总数
                .validOrderCountList(validOrderString)  //每日有效订单数，
                .validOrderCount(validOrderTotal).build();

        return build;

    }


    /**
     * 查询销量排名top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO orderTop10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> datalist = orderMapper.orderTop10Statistics(beginTime,endTime);
        List<String> nameList = datalist.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = datalist.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String nameString = StringUtils.join(nameList, ",");
        String numberString = StringUtils.join(numberList, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameString)
                .numberList(numberString)
                .build();
    }

    /**
     * 导出近30天的数据
     * @param response
     */
    public void exportData(HttpServletResponse response) throws IOException {
        //获取到近30天的数据
        LocalDate nowDate = LocalDate.now();  //获取到当前日期
        LocalDate beforeDay = nowDate.minusDays(1);  //获取到前一天的日期
        LocalDate before30Day = nowDate.minusDays(30); //获取到前30天的日期
        LocalDateTime begin = LocalDateTime.of(before30Day, LocalTime.MIN);//前30天的开始 00:00:00
        LocalDateTime end = LocalDateTime.of(beforeDay, LocalTime.MAX);//前一天的结束 23:59:59
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
//获取到excel对象
        InputStream is = new FileInputStream
(new File("E:\\project\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx"));
        XSSFWorkbook excel = new XSSFWorkbook(is);
        //获取到第一个标签页的对象
        XSSFSheet sheet1 = excel.getSheet("Sheet1");
        sheet1.getRow(1).getCell(1).setCellValue("日期:" + beforeDay + "至" +before30Day);
        sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
        sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
        sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
        sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
        sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
        for (int i = 0; i < 30; i++) {
            LocalDateTime beginTime = LocalDateTime.of(before30Day, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(before30Day, LocalTime.MAX);
            BusinessDataVO businessData1 = workspaceService.getBusinessData(beginTime, endTime);
            sheet1.getRow(7+i).getCell(1).setCellValue(before30Day.toString());
            sheet1.getRow(7+i).getCell(2).setCellValue(businessData1.getTurnover());
            sheet1.getRow(7+i).getCell(3).setCellValue(businessData1.getValidOrderCount());
            sheet1.getRow(7+i).getCell(4).setCellValue(businessData1.getOrderCompletionRate());
            sheet1.getRow(7+i).getCell(5).setCellValue(businessData1.getUnitPrice());
            sheet1.getRow(7+i).getCell(6).setCellValue(businessData1.getNewUsers());

            before30Day = before30Day.plusDays(1);
        }
        //写出到浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);

        //关闭资源
        excel.close();
        outputStream.close();
    }
}
